package site.sorghum.ddl.wood;

import org.noear.wood.annotation.Column;
import org.noear.wood.annotation.Exclude;
import org.noear.wood.annotation.PrimaryKey;
import org.noear.wood.annotation.Table;
import site.sorghum.ddl.base.JavaCoreEntityGenerate;
import site.sorghum.ddl.entity.DdlColumnWrap;
import site.sorghum.ddl.entity.DdlTableWrap;
import site.sorghum.ddl.extra.ClassUtil;

import java.lang.reflect.Field;
import java.util.List;

public class WoodEntityGenerate extends JavaCoreEntityGenerate {


    /**
     * Java的类 -> 数据库表元数据
     *
     * @param tClass 类名
     * @return 数据库表元数据
     */
    @Override
    public DdlTableWrap get(Class<?> tClass) {
        DdlTableWrap coreDdlTableWrap = getCoreDdlTableWrap(tClass);
        Table table = tClass.getAnnotation(Table.class);
        if (table != null && table.value() != null && !table.value().isEmpty()) {
            coreDdlTableWrap.setName(table.value());
        }
        List<Field> fields = ClassUtil.fetchAllFields(tClass);
        for (Field field : fields) {
            DdlColumnWrap coreDdlColumnWrap = getCoreDdlColumnWrap(coreDdlTableWrap.getName(), field, coreDdlTableWrap.getPks());
            if (coreDdlColumnWrap == null) {
                continue;
            }
            Exclude exclude = field.getAnnotation(Exclude.class);
            if (exclude != null) {
                continue;
            }
            Column columnAnnotation = field.getAnnotation(Column.class);
            if (columnAnnotation != null && columnAnnotation.value() != null && !columnAnnotation.value().isEmpty()) {
                coreDdlColumnWrap.setName(columnAnnotation.value());
            }
            PrimaryKey primaryKey = field.getAnnotation(PrimaryKey.class);
            if (primaryKey != null) {
                boolean contains = coreDdlTableWrap.getPks().contains(coreDdlColumnWrap.getName());
                if (!contains) {
                    coreDdlTableWrap.getPks().add(coreDdlColumnWrap.getName());
                }
            }
            coreDdlTableWrap.getColumns().add(coreDdlColumnWrap);
        }
        resort(coreDdlTableWrap.getColumns());
        return coreDdlTableWrap;
    }

}
